package com.ljh.lottery.service.activitystatus.operator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ljh.lottery.mapper.ActivityMapper;
import com.ljh.lottery.mapper.ActivityPrizeMapper;
import com.ljh.lottery.pojo.dataobject.ActivityDO;
import com.ljh.lottery.pojo.dataobject.ActivityPrizeDO;
import com.ljh.lottery.service.dto.ConvertActivityStatusDTO;
import com.ljh.lottery.service.enums.ActivityPrizeStatusEnum;
import com.ljh.lottery.service.enums.ActivityStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: Themberfue
 * @date: 2025/4/17 10:40
 * @description:
 */
@Component
public class ActivityOperator extends AbstractActivityOperator{
    @Autowired
    ActivityMapper activityMapper;

    @Autowired
    ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 2;
    }

    @Override
    public Boolean needConvert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        // TODO 1. 校验参数
        Long activityId = convertActivityStatusDTO.getActivityId();
        ActivityStatusEnum activityStatusEnum = convertActivityStatusDTO.getTargetActivityStatus();
        if (null == activityId
                || null == activityStatusEnum) {
            return false;
        }

        // TODO 2. 检验其是否需要扭转状态
        ActivityDO activityDO = activityMapper.selectById(activityId);
        if (null == activityDO) {
            return false;
        }
        if (activityDO.getStatus()
                .equalsIgnoreCase(activityStatusEnum.name())) {
            return false;
        }

        // TODO 3. 检验是否所有奖品都被抽完 -> 查询状态为 INIT 的奖品
        QueryWrapper<ActivityPrizeDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                    .eq(ActivityPrizeDO::getActivityId, activityId)
                    .eq(ActivityPrizeDO::getStatus, ActivityPrizeStatusEnum.INIT.name());
        return activityPrizeMapper.selectCount(queryWrapper) <= 0;
    }

    @Override
    public Boolean convert(ConvertActivityStatusDTO convertActivityStatusDTO) {
        try {
            UpdateWrapper<ActivityDO> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda()
                    .set(ActivityDO::getStatus, convertActivityStatusDTO.getTargetActivityStatus().name())
                    .eq(ActivityDO::getId, convertActivityStatusDTO.getActivityId());
            activityMapper.update(updateWrapper);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
